package org.sample.commons.jpa;

import org.sample.commons.bean.BeanUtils;

import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;
import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.util.Map;

public class DateEntityListener {

    @PrePersist
    public void touchForCreate(Object target) {
        Map<String, BeanUtils.PropertyMethod> methodMap = BeanUtils.getPropertyMethod(target.getClass());

        for (Map.Entry<String, BeanUtils.PropertyMethod> entry : methodMap.entrySet()) {
            BeanUtils.PropertyMethod propertyMethod = entry.getValue();

            Method readMethod = propertyMethod.getReadMethod();

            if (readMethod.getAnnotation(CreatedAt.class) != null)
                BeanUtils.setValue(target, propertyMethod.getWriteMethod(), LocalDateTime.now());

            if (readMethod.getAnnotation(LastModified.class) != null)
                BeanUtils.setValue(target, propertyMethod.getWriteMethod(), LocalDateTime.now());

        }
    }

    @PreUpdate
    public void touchForUpdate(Object target) {
        Map<String, BeanUtils.PropertyMethod> methodMap = BeanUtils.getPropertyMethod(target.getClass());

        for (Map.Entry<String, BeanUtils.PropertyMethod> entry : methodMap.entrySet()) {
            BeanUtils.PropertyMethod propertyMethod = entry.getValue();
            Method readMethod = propertyMethod.getReadMethod();
            if (readMethod.getAnnotation(LastModified.class) != null)
                BeanUtils.setValue(target, propertyMethod.getWriteMethod(), LocalDateTime.now());
        }
    }
}